package com.zmxstudy.rbac.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:tianyu
 * @Date:2024-06-09 10:16
 */
public class EntityUtil {
    /**
     * 获取实体类的属性和值，并转换为Map
     *
     * @param entity 实体类
     * @return Map<String, Object>
     */
    public static Map<String, Object> getPropertyMap(Object entity) {
        HashMap<String, Object> map = new HashMap<>(16);
        for (Method method : entity.getClass().getDeclaredMethods()) {
            String methodName = method.getName();
            if (methodName.startsWith("get") || methodName.startsWith("is")) {
                try {
                    Object value = method.invoke(entity);
                    if (ObjectUtil.isNotEmpty(value)) {
                        String columnName = StrUtil.toUnderlineCase(methodName.replaceFirst("get|is", ""));
                        map.put(columnName, value);
                    }
                } catch (Exception ignored) {
                }
            }
        }
        return map;

    }
}
